package com.igame.Service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.igame.Service.CommonService;
import com.igame.Service.GoodsService;
import com.igame.common.PageResult;
import com.igame.common.Result;
import com.igame.constant.GoodsConstant;
import com.igame.constant.OrderConstant;
import com.igame.dto.DeleteCarGoodsDao;
import com.igame.dto.GoodsDao;
import com.igame.dto.GoodsPageQueryDto;
import com.igame.dto.HistoryDto;
import com.igame.entity.*;
import com.igame.mapper.*;
import com.igame.vo.GoodsVo;
import com.igame.vo.ShoppingCartVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    CategoriesMapper categoriesMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    private RedisTemplate<String, HistoryDto> redisTemplate;

    @Autowired
    private CommonService commonService;

    @Autowired
    private GoodsImgMapper goodsImgMapper;

    @Override
    public PageResult pageQuery(GoodsPageQueryDto goodsPageQueryDto, String name) {
        // 拼接百分号符号
        String searchPattern = "%" + name + "%";
        goodsPageQueryDto.setName(searchPattern);

        // 使用分页助手
        PageHelper.startPage(goodsPageQueryDto.getPage(), goodsPageQueryDto.getPageSize());
        Page<Goods> page = goodsMapper.pageQuery(goodsPageQueryDto);

        // 获取总数和结果
        long total = page.getTotal();
        List<Goods> records = page.getResult();
        return new PageResult(total, records);
    }

    @Override
    public Result<List<Goods>> goodsList(GoodsDao goodsDao) {
        List<Goods> goodsList = goodsMapper.goodsList(goodsDao);
        return Result.success(goodsList);
    }

    @Override
    public Result<GoodsVo> getGoodsById(Integer id) {
        GoodsVo goodsVo =new GoodsVo();

        Goods goods = goodsMapper.getGoodsById(id);


        BeanUtils.copyProperties(goods,goodsVo);
//        设置商品相关内容
        if (goods.getFreePost()==0){
            goodsVo.setFreePost(GoodsConstant.IsFree);
        }else {
            goodsVo.setFreePost(GoodsConstant.NotFree);
        }

        if (goods.getPacka()==0){
            goodsVo.setPacka(GoodsConstant.IsPackage);
        }else {
            goodsVo.setPacka(GoodsConstant.NotPackage);
        }

        switch (goods.getVersion()) {
            case 1 -> goodsVo.setVersion(GoodsConstant.China);
            case 2 -> goodsVo.setVersion(GoodsConstant.HongKong);
            case 3 -> goodsVo.setVersion(GoodsConstant.Japanese);
            case 4 -> goodsVo.setVersion(GoodsConstant.America);
            case 5 -> goodsVo.setVersion(GoodsConstant.Europe);
        }

        switch (goods.getFineness()) {
            case 1 -> goodsVo.setFineness(GoodsConstant.high);
            case 2 -> goodsVo.setFineness(GoodsConstant.medium);
            case 3 -> goodsVo.setFineness(GoodsConstant.low);
            case 4 -> goodsVo.setFineness(GoodsConstant.zero);
        }

        if (goods.getState()==0){
            goodsVo.setState(GoodsConstant.onSale);
        }else {
            goodsVo.setState(GoodsConstant.sole);
        }
        return Result.success(goodsVo);
    }

    @Override
    @Transactional
    public Result insertToCar(ShoppingCart cartObj) {
        Result result = new Result();
        try {
            if (goodsMapper.isInCar(cartObj.getUserId(), cartObj.getGoodsId())!=null){
                throw new RuntimeException("该商品已经添加过了哦");
            }
            int insert = goodsMapper.insert(cartObj);
            if (insert==0){
                throw new RuntimeException("数据插入失败，请稍后再试");
            }
            result.setState(true);
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.setState(false);
            result.setErrMessage(e.getMessage());
        }
        return  result;
    }

    @Override
    public Result<List<ShoppingCartVo>> getCarGoods(Integer userId) {
        List<Integer> list = goodsMapper.findCar(userId);
        List<ShoppingCartVo> shoppingCartVoList = new ArrayList<>();
        for (Integer id : list) {
            Goods goods = goodsMapper.getGoodsById(id);
            String categories = categoriesMapper.selectById(goods.getCategoriesId());
            // 创建一个新的 ShoppingCartVo 实例
            ShoppingCartVo shoppingCartVo = new ShoppingCartVo();
            // 拷贝属性
            BeanUtils.copyProperties(goods, shoppingCartVo);
            shoppingCartVo.setUserName(goods.getCreateUser());
            shoppingCartVo.setGoodsName(goods.getName());
            shoppingCartVo.setCategories(categories);
            shoppingCartVo.setGoodsId(goods.getId());
            // 添加到列表
            shoppingCartVoList.add(shoppingCartVo);
        }
        return Result.success(shoppingCartVoList);
    }

    @Override
    @Transactional
    public Result deleteCarGoods(DeleteCarGoodsDao dao) {
        int i=0;
        List<Integer> goodsId = dao.getGoodsId();
        for (Integer integer : goodsId) {
             i= goodsMapper.deleteCarGoods(dao.getUserId(),integer);
        }
        Result result =new Result();
        try {
            if (i==0){
                throw new RuntimeException("删除失败,请稍后再试");
            }
            result.setState(true);
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.setState(false);
            result.setErrMessage(e.getMessage());
        }
        return result;
    }

    @Override
    public Result<List<GoodsVo>> getIPosted(Integer id) {
        String nameById = userMapper.getNameById(id);
        List<Goods> goodsList = goodsMapper.selectByUserName(nameById);
        List<GoodsVo> goodsVoList =new ArrayList<>();
        for (Goods goods : goodsList) {
            GoodsVo goodsVo =new GoodsVo();
            BeanUtils.copyProperties(goods,goodsVo);
            if(goods.getState()==0){
                goodsVo.setState(GoodsConstant.onSale);
            }else {
                goodsVo.setState(GoodsConstant.sole);
            }
            goodsVoList.add(goodsVo);
        }
        return Result.success(goodsVoList);
    }

    @Override
    public Result<List<GoodsVo>> iSold(Integer id) {
        String nameById = userMapper.getNameById(id);
        List<Goods> goodsList = goodsMapper.selectByUserNameAndState(nameById);
        List<GoodsVo> goodsVoList =new ArrayList<>();
        for (Goods goods : goodsList) {
            GoodsVo goodsVo =new GoodsVo();
            BeanUtils.copyProperties(goods,goodsVo);
            if(goods.getState()==0){
                goodsVo.setState(GoodsConstant.onSale);
            }else {
                goodsVo.setState(GoodsConstant.sole);
            }
            goodsVoList.add(goodsVo);
        }
        return Result.success(goodsVoList);
    }

    @Override
    public Result<List<GoodsVo>> buyFormCar(Integer[] ids) {
        List<GoodsVo> goodsVoList =new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            Goods goods = goodsMapper.getGoodsById(ids[i]);
            GoodsVo goodsVo =new GoodsVo();
            BeanUtils.copyProperties(goods,goodsVo);
            if(goods.getState()==0){
                goodsVo.setState(GoodsConstant.onSale);
            }else {
                goodsVo.setState(GoodsConstant.sole);
            }
            goodsVoList.add(goodsVo);
        }
        return Result.success(goodsVoList);
    }

    @Override
    public Result<GoodsVo> soloBuy(Integer id) {
        Goods goods = goodsMapper.getGoodsById(id);

        GoodsVo goodsVo =new GoodsVo();
        BeanUtils.copyProperties(goods,goodsVo);
        if(goods.getState()==0){
            goodsVo.setState(GoodsConstant.onSale);
        }else {
            goodsVo.setState(GoodsConstant.sole);
        }

        return Result.success(goodsVo);
    }
//查找未付款的商品
    @Override
    public Result<List<GoodsVo>> selectObligation(Integer userId) {
        List<Integer> integers = orderMapper.selectByState(userId, OrderConstant.obligation);

        List<GoodsVo> goodsVoList =new ArrayList<>();
        for (Integer integer : integers) {
            GoodsVo goodsVo =new GoodsVo();
            Goods goods = goodsMapper.getGoodsById(integer);
            BeanUtils.copyProperties(goods,goodsVo);
            goodsVoList.add(goodsVo);
        }
        return Result.success(goodsVoList);
    }

    @Override
    public Result<List<GoodsVo>> selectPendingReceipt(Integer userId) {
        List<Integer> integers = orderMapper.selectByState(userId, OrderConstant.pendingReceipt);
        List<GoodsVo> goodsVoList =new ArrayList<>();
        for (Integer integer : integers) {
            GoodsVo goodsVo =new GoodsVo();
            Goods goods = goodsMapper.getGoodsById(integer);
            BeanUtils.copyProperties(goods,goodsVo);
            goodsVoList.add(goodsVo);
        }
        return Result.success(goodsVoList);
    }

    @Override
    public Result<List<GoodsVo>> getCompleted(Integer userId) {
        List<Integer> integers = orderMapper.selectByState(userId, OrderConstant.Completed);
        List<GoodsVo> goodsVoList =new ArrayList<>();
        for (Integer integer : integers) {
            GoodsVo goodsVo =new GoodsVo();
            Goods goods = goodsMapper.getGoodsById(integer);
            BeanUtils.copyProperties(goods,goodsVo);
            goodsVoList.add(goodsVo);
        }
        return Result.success(goodsVoList);
    }

    @Override
    public void sendGoodsIdToRedis(HistoryDto historyDto) {
         final String REDIS_KEY = "historyZSet";
         final long MAX_SIZE = 20;
         final long EXPIRE_TIME = 7; // 7天
        // 使用当前时间戳作为排序的分数
        long score = System.currentTimeMillis();

        ZSetOperations<String, HistoryDto> zSetOps = redisTemplate.opsForZSet();

        // 添加HistoryDto到ZSET，使用score作为排序分数
        zSetOps.add(REDIS_KEY, historyDto, score);

        // 如果ZSET的元素数量超过了20，删除排名最靠前的元素
        Long size = zSetOps.size(REDIS_KEY);
        if (size != null && size > MAX_SIZE) {
            zSetOps.removeRange(REDIS_KEY, 0, size - MAX_SIZE - 1);
        }

        // 设置ZSET的过期时间为1周
        redisTemplate.expire(REDIS_KEY, EXPIRE_TIME, TimeUnit.DAYS);
    }

    @Override
    public Result<List<GoodsVo>> getHistory(Integer userId) {
        final String REDIS_KEY = "historyZSet";
        ZSetOperations<String, HistoryDto> zSetOps = redisTemplate.opsForZSet();
        Set<HistoryDto> historySet = zSetOps.range(REDIS_KEY, 0, -1);

        List<Integer> goodsIds = new ArrayList<>();
//        筛选和当前登录用户id相同的内容
        if (historySet != null) {
            for (HistoryDto historyDto : historySet) {
                if (historyDto.getUserId().equals(userId)) {
                    goodsIds.add(historyDto.getGoodsId());
                }
            }
        }

        List<GoodsVo> goodsVoList =new ArrayList<>();
        for (Integer goodsId : goodsIds) {
            GoodsVo goodsVo =new GoodsVo();
            Goods goods = goodsMapper.getGoodsById(goodsId);
            BeanUtils.copyProperties(goods,goodsVo);
            goodsVoList.add(goodsVo);
        }

        return Result.success(goodsVoList);
    }

    @Override
    public Result<List<FreePost>> getAllFreePost() {
        return Result.success(goodsMapper.selectAllFreePost());
    }

    @Override
    public Result<List<Fineness>> getAllFineness() {
        return Result.success(goodsMapper.selectAllFineness());
    }

    @Override
    public Result<List<Pack>> getAllPack() {
        return Result.success(goodsMapper.selectAllPack());
    }

    @Override
    public Result<List<Version>> getAllVersion() {
        return Result.success(goodsMapper.selectAllVersion());
    }

    @Override
    public Result<List<Platform>> getAllPlatform() {
        return Result.success(goodsMapper.selectAllPlatform());
    }

//    description 简介 introduction 详细
    @Override
    @Transactional
    public Result addGoods(String name, String description, BigDecimal price, Integer categoryId, Integer freePostId, Integer pageOptionId, Integer conditionId, Integer versionId, Integer platformId, String introduction, Integer loginId, MultipartFile coverImage, List<MultipartFile> images) {
        try {
            Goods goods =new Goods();
            Integer id = goodsMapper.selectNewId()+1;
            goods.setId(id);
            goods.setName(name);
            goods.setBlurb(description);
            goods.setPrice(price);
            goods.setCategoriesId(categoryId);
            goods.setFreePost(freePostId);
            goods.setPacka(pageOptionId);
            goods.setFineness(conditionId);
            goods.setVersion(versionId);
            if (price==null){
                throw new RuntimeException("请输入正确的价钱");
            }
            if (platformId==1)
            {
                goods.setPlatform(GoodsConstant.Nintendo);
            } else if (platformId==2) {
                goods.setPlatform(GoodsConstant.Playstation);
            }else {
                goods.setPlatform(GoodsConstant.XBox);
            }
            goods.setIntro(introduction);

            goods.setCreateTime(LocalDateTime.now());

            String username = userMapper.getNameById(loginId);

            goods.setCreateUser(username);

            goods.setState(0);
            if (coverImage!=null){
                String upload = commonService.upload(coverImage);
                goods.setImgPath(upload);
            }
            goodsMapper.insertGoods(goods);

            if (images.size()>0){
                for (MultipartFile image : images) {
                    GoodsImg goodsImg =new GoodsImg();
                    goodsImg.setGoodsId(id);

                    String upload = commonService.upload(image);
                    goodsImg.setGoodsImg(upload);
                    goodsImgMapper.addGoodsImg(goodsImg);
                }
            }
            return Result.success();
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("错误");
        }
    }
}
